package com.flycms.web.system.rest;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.flycms.constant.StatusConst;
import com.flycms.core.base.BaseController;
import com.flycms.core.entity.PagingParam;
import com.flycms.core.entity.RestDataVo;
import com.flycms.core.utils.web.utils.CommonUtils;
import com.flycms.module.qasystem.model.Answers;
import com.flycms.module.qasystem.model.Questions;
import com.flycms.module.qasystem.service.AnswersService;
import com.flycms.module.qasystem.service.QuestionsService;

/**
 * 文章系统的后台管理
 * <br/>Copyright 2020
 * <br/>All rights reserved
 * @author 沁言訫語
 * @version 2020年3月4日
 * @Date 2020年3月4日
 */

@RestController
@RequestMapping("/system/qa")
public class AdminQAController extends BaseController {

    private static final Logger logger = LogManager.getLogger(AdminQAController.class);
    
    @Autowired
    protected QuestionsService questionService;
    
    @Autowired
    protected AnswersService answerService;
    
    /**
     * 管理员查看问题列表
     * @param status
     * @param title
     * @param paging
     * @return
     * @author 沁言訫語
     */
    
    @GetMapping(value = { "/question/list" })
    public RestDataVo getQuestionListForAdmin(
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "title", required = false) String title,
            @RequestParam(value = "userId", required = false) Long userId,
            @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        PagingParam paging = CommonUtils.validParam(pageIndex, pageSize);
        status = CommonUtils.validStatus(status);
        RestDataVo rest = null;
        try {
            List<Questions> questList = questionService.getQuestionList(userId, status, title, paging.getOrderBy(),
                    paging.getOrder(), paging.getOffset(), paging.getRows());
            int count = questionService.getQuestionCount(userId, title, status);
            rest = RestDataVo.PAGE(questList, paging.getPageIndex(), paging.getPageSize(), count);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("获取问题列表异常");
        }
        return rest;
    }
    
    @GetMapping(value = {"/question/info/{id}"})
    public RestDataVo getQuestionDetail(@PathVariable(value = "id") Long id) {
        RestDataVo rest = null;
        try {
            Questions quest = questionService.queryQuestionById(id);
            if (quest != null) {
                rest = RestDataVo.OK(quest);
            } else {
                rest = RestDataVo.ERROR("为查询到id为{}的问题", id + "");
            }
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("获取问题异常");
        }
        return rest;
    }

    @GetMapping(value = {"/answer/info/{id}"})
    public RestDataVo getAnswerDetail(@PathVariable(value = "id") Long id) {
        RestDataVo rest = null;
        try {
            Answers ans = answerService.queryAnswerById(id, null);
            if (ans == null) {
                rest = RestDataVo.ERROR("不存在id为{0}的回答", id + "");
            } else {
                rest = RestDataVo.OK(ans);
            }
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("获取回答异常");
        }
        return rest;
    }
    
    /**
     * 管理员查看回答列表
     * @param status
     * @param questionId
     * @param paging
     * @return
     * @author 沁言訫語
     */
    
    @GetMapping(value = {"/answer/list"})
    public RestDataVo getAnswerList(@RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "questionId", required = false) Long questionId,
            @RequestParam(value = "userId", required = false) Long userId,
            @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        PagingParam paging = CommonUtils.validParam(pageIndex, pageSize);
        status = CommonUtils.validStatus(status);
        RestDataVo rest = null;
        try {
            List<Answers> questList = answerService.getAnswerList(userId, questionId, status, paging.getOrderBy(),
                    paging.getOrder(), paging.getOffset(), paging.getRows());
            int count = answerService.getAnswerCount(userId, questionId, status);
            rest = RestDataVo.PAGE(questList, paging.getPageIndex(), paging.getPageSize(), count);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("获取问题列表异常");
        }
        return rest;
    }
    
    /**
     * 管理员审核问题
     * @param id
     * @param audit
     * @param opinion
     * @return
     * @author 沁言訫語
     */
    
    @PostMapping(value = {"/question/audit/{id}"})
    public RestDataVo auditQuestion(@PathVariable(value = "id") Long id,
            @RequestParam(value = "audit") Boolean audit,
            @RequestParam(value = "opinion", required = false) String opinion) {
        //校验参数 与questions中相同
//        String opinion = "";
//        if (map != null && map.containsKey("opinion")) {
//            opinion = CommonUtils.transToString(map.get("opinion"));
//            if (opinion.length() > 200) {
//                return RestDataVo.ERROR("审核意见不能超过200");
//            }
//        }
        RestDataVo rest = null;
        Long updateUserId = getAdminUserId();
        try {
            Questions quest = questionService.queryQuestionById(id);
            if (quest == null) {
                rest = RestDataVo.ERROR("未找到id:{0}的问题", id);
                return rest;
            }
            Integer status = null;
            if (Objects.equals(audit, true)) {
                status = StatusConst.OPEN.value();
            } else {
                status = StatusConst.CLOSE.value();
            }
            questionService.auditQuestion(id, status, opinion, new Date(), updateUserId);
            rest = RestDataVo.OK("审核问题成功");
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("审核问题异常，" + e.getMessage());
        }
        return rest;
    }
    
    /**
     * 管理员审核答案
     * @param id
     * @param audit
     * @param opinion
     * @return
     * @author 沁言訫語
     */
    
    @PostMapping(value = {"/answer/audit/{id}"})
    public RestDataVo auditAnswer(@PathVariable(value = "id") Long id,
            @RequestParam(value = "audit") Boolean audit,
            @RequestParam(value = "opinion", required = false) String opinion) {
        //校验参数 与answers中相同
//        String opinion = "";
//        if (map != null && map.containsKey("opinion")) {
//            opinion = CommonUtils.transToString(map.get("opinion"));
//            if (opinion.length() > 200) {
//                return RestDataVo.ERROR("审核意见不能超过200");
//            }
//        }
        RestDataVo rest = null;
        Long updateUserId = getAdminUserId();
        try {
            Answers answer = answerService.queryAnswerById(id, null);
            if (answer == null) {
                rest = RestDataVo.ERROR("未找到id:{0}的答案", id);
                return rest;
            }
            Integer status = null;
            if (Objects.equals(audit, true)) {
                status = StatusConst.OPEN.value();
            } else {
                status = StatusConst.CLOSE.value();
            }
            answerService.auditAnswer(id, status, opinion, new Date(), updateUserId);
            rest = RestDataVo.OK("审核答案成功");
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("审核答案异常，" + e.getMessage());
        }
        return rest;
    }
    
    @PostMapping(value = {"/answer/remove/{id}"})
    public RestDataVo removeAnswer(@PathVariable(value = "id") Long id) {
        RestDataVo rest = null;
        try {
            Answers ans = answerService.queryAnswerById(id, null);
            if (ans == null) {
                rest = RestDataVo.ERROR("回答不存在");
            } else {
                Long updateUserId = getAdminUserId();
                Answers a = answerService.queryAnswerById(id, null);
                if (a == null || Objects.equals(a.getStatus(), StatusConst.DELETE.value())) {
                    answerService.removeAnswerById(id, null);
                    rest = RestDataVo.OK("删除回答成功");
                } else {
                    answerService.editAnswer(ans.getId(), null, StatusConst.DELETE.value(), new Date(), updateUserId);
                    rest = RestDataVo.OK("改变回答状态为删除成功");
                }
            }
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("删除回答异常");
        }
        return rest;
    }
    
    @PostMapping(value = {"/question/remove/{id}"})
    public RestDataVo removeQuestion(@PathVariable(value = "id") Long id) {
        RestDataVo rest = null;
        try {
            Questions quest = questionService.queryQuestionById(id);
            if (quest == null) {
                rest = RestDataVo.ERROR("问题不存在");
                return rest;
            } else {
                Long updateUserId = getAdminUserId();
                Questions q = questionService.queryQuestionById(id);
                if (q == null || Objects.equals(q.getStatus(), StatusConst.DELETE.value())) {
                    questionService.removeQuestion(id);
                    rest = RestDataVo.OK("删除问题成功");
                } else {
                    questionService.editQuestions(id, StatusConst.DELETE.value(), new Date(), updateUserId);
                    rest = RestDataVo.OK("改变问题状态为删除成功");
                }
            }
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("删除问题异常");
        }
        return rest;
    }
    
}
